package hu.vpszd.beans;


import hu.vpszd.VpszdMailSender
import hu.vpszd.entities.customer.CheckingAccount
import hu.vpszd.entities.customer.Customer
import hu.vpszd.entities.transaction.Transaction
import hu.vpszd.services.CustomerService

import javax.faces.bean.SessionScoped

import org.primefaces.model.chart.CartesianChartModel
import org.primefaces.model.chart.ChartSeries
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
@SessionScoped
public class ChartBean implements Serializable {

	private CartesianChartModel categoryModel;

	@Autowired
	private CustomerMaintBean cmb
	@Autowired
	private VpszdMailSender mailSender
	@Autowired
	private CustomerService customerService;


	public CartesianChartModel getCategoryModel() {
		CartesianChartModel categoryModel = new CartesianChartModel();

		Customer customer = customerService.find(cmb.customer.id)
		List<CheckingAccount> cas = customer.checkingAccounts

		for (ca in cas) {
			ChartSeries series = new ChartSeries();
			series.setLabel(ca.bankAccountNumber);

			if(ca.incomingTransactions.isEmpty() && ca.outgoingTransactions.isEmpty()){
				Transaction t1 = new Transaction(sum: 0, date: new Date())
				Transaction t2 = new Transaction(sum: 0, date: new Date())
				ca.incomingTransactions.add(t1)
				ca.outgoingTransactions.add(t2)
			}
			
			ca.incomingTransactions.each { t ->
				series.set(t.date, t.sum)
			}

			ca.outgoingTransactions.each { t ->
				series.set(t.date, -1 * t.sum)
			}
			
			categoryModel.addSeries(series);
		}
		
		return categoryModel
	}

	protected void refreshChart() {
		Customer customer = customerService.find(cmb.customer.id)
		List<CheckingAccount> cas = customer.checkingAccounts
		ChartSeries series = new ChartSeries();
		Date date = new Date()
		for (ca in cas) {
			series.setLabel(ca.bankAccountNumber);

			ca.incomingTransactions.each { t ->
				series.set(t.date = date, t.sum = 0)
			}

			ca.outgoingTransactions.each { t ->
				series.set(t.date = date, t.sum = 0)
			}
		}
		categoryModel.addSeries(series);
	}
}